
<template>
    <div class="container">
        <!-- 搜索和筛选区域 -->
        <section class="filter-section">
            <div class="search-container">
                <input type="text" v-model="queryParam.title" class="search-input" placeholder="搜索文章...">
                <button @click="getPostsList" class="search-button">搜索</button>
            </div>
            
            <div class="category-filter">
                <div class="category-tag"
                :class="{ active:tagselIndex === null }"
                @click="tagClick(null,null)"
                >全部</div>
                <div
                v-for="(item,index) in tags"
                 :key="index"
                  class="category-tag"
                  :class="{ active: tagselIndex === index }"
                  @click="tagClick(index,item)"
                  >{{ item }}</div>
            </div>
        </section>

        <!-- 文章列表 -->
        <section class="article-list">
            <!-- 文章项1 -->
            <article class="article-card" @click="router.push({path:'/article/'+item.id})" v-for="(item,index) in postsList" :key="index">
                <div class="article-image-container">
                    <img :src="getImageUrl(item.coverImg)" alt="Hello World" class="article-image">
                </div>
                <div class="article-content">
                    <h3 class="article-title">{{ item.title }}</h3>
                    <div class="article-category">
                        <span v-for="(item,index) in item.tagCodes" :key="index">{{item}}</span>
                    </div>
                    <p class="article-excerpt">
                        {{ item.excerpt }}
                    </p>
                    <div class="article-meta">
                        <span>{{ item.viewCount }} 阅读</span>
                        <span>{{ item.createTime }}</span>
                    </div>
                    <!-- <a href="#" class="read-more">阅读更多</a> -->
                </div>
            </article>
        </section>

        <!-- 分页 -->
        <nav class="pagination">
            <li class="page-item"><button @click="prevPage" class="page-link">上一页</button></li>
            <li v-for="(page,index) in pages" :key="index" 
            @click="goToPage(page)"
            class="page-item">
                <button class="page-link" :class="{ active: currentPage === page }">{{ page }}</button>
            </li>
            <li class="page-item"><button @click="nextPage" class="page-link">下一页</button></li>
        </nav>
    </div>
</template>

<script setup name="articles">
import { computed, onMounted, ref } from 'vue';
import { getTags,getPosts } from "@/api/articles"
import { useRoute,useRouter } from 'vue-router'
import { getImageUrl } from '@/utils/imageHelp'
import { message } from '@/utils/message'
import { useHead } from '@vueuse/head';
const router = useRouter ()
const route = useRoute()
const tags = ref([])
const tagselIndex = ref(null)
const postsList = ref([])
const listTotal = ref(0)
const PageSize = ref(10);
const currentPage = ref(1);

const totalPages = computed(() => 
  Math.ceil(listTotal.value / PageSize.value)
);

//页码数组
const pages = computed(() => {
    const pageTotal = totalPages.value; // 总页数
    const current = currentPage.value;   // 当前页
    const maxVisible = 10;              // 最大显示页码数
    let range = [];

    if (pageTotal <= maxVisible) {
      // 总页数<=10：显示所有页码
      for (let i = 1; i <= pageTotal; i++) range.push(i);
    } else {
      // 总页数>10：动态截取页码范围
      const left = Math.max(1, current - Math.floor(maxVisible / 2));
      const right = Math.min(pageTotal, left + maxVisible - 1);

      // 确保始终显示10个页码（避免左右偏移不足）
      if (right - left + 1 < maxVisible) {
        if (current < pageTotal / 2) {
          range = Array.from({ length: maxVisible }, (_, i) => i + 1);
        } else {
          range = Array.from({ length: maxVisible }, (_, i) => pageTotal - maxVisible + i + 1);
        }
      } else {
        for (let i = left; i <= right; i++) range.push(i);
      }

      // 添加省略号逻辑（可选）
      if (range[0] > 1) {
        range.unshift('...'); // 头部添加省略号
        range.unshift(1);    // 确保第一页始终显示
      }
      if (range[range.length - 1] < pageTotal) {
        range.push('...');    // 尾部添加省略号
        range.push(pageTotal); // 确保最后一页始终显示
      }
    }
    return range;
});


// 上一页
function prevPage() {
  if (currentPage.value > 1){ 
    currentPage.value--;
    getPostsList()
  }else{
    return false;
  }
}

//下一页
function nextPage() {
  if (currentPage.value < totalPages.value) {
    currentPage.value++;
    getPostsList()
  }else{
    return false;
  }
}

//转到某页
function goToPage(page) {
  currentPage.value = page;
  getPostsList()
}

const queryParam = ref({
    pageNum:1,
    pageSize:10
})

const tagClick = (index,item) =>{
    tagselIndex.value = index
    queryParam.value.tag = item
    getPostsList()
}

const getTagList = () => {
    getTags().then(response => {
        tags.value = response.data
    })
}

const getPostsList = () => {
    queryParam.value.pageNum = currentPage
    queryParam.value.pageSize = PageSize
    getPosts(queryParam.value).then(response => {
        if(response.code === 200){
            postsList.value = response.rows
            listTotal.value = response.total
        }
    }).catch(error => {
        message.warning(error.message, 3000)
    })
}

const seoData = computed(() => ({
  meta: [
    {
      name: 'description',
      content: '空指针的夜晚 这里是文章列表，包含不同分类的文章内容，希望对您有帮助。' 
    },
    {
      name: 'keywords',
      content: '文章列表'
    }
  ]
}))

useHead(seoData)

onMounted(() => {
    getTagList()
    queryParam.value.title = route.query.title
    getPostsList()
})
</script>

<style scoped>
    .container{
        padding: 5rem 15px;
        text-align: left;
    }
    /* 筛选区域 */
    .filter-section {
        background-color: var(--white);
        padding: 20px;
        border-radius: var(--radius-md);
        box-shadow: var(--shadow-sm);
        margin-bottom: 30px;
        gap: 20px;
        align-items: center;
    }

    .search-container {
        flex: 1;
        min-width: 300px;
        display: flex;
    }

    .search-input {
        flex: 1;
        padding: 10px 15px;
        border: 1px solid #ddd;
        border-radius: var(--radius-sm) 0 0 var(--radius-sm);
        font-size: 16px;
        outline: none;
        transition: border-color 0.3s;
    }

    .search-input:focus {
        border-color: var(--primary-color);
    }

    .search-button {
        outline: none;
        padding: 0 20px;
        background-color: #333;
        color: white;
        border: none;
        border-radius: 0 var(--radius-sm) var(--radius-sm) 0;
        cursor: pointer;
        transition: background-color 0.3s;
    }

    .search-button:hover {
        background-color: #4CAF50;
        color: #333;
    }

    .category-filter {
        margin-top: 1rem;
        min-width: 300px;
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
    }

    .category-tag {
        padding: 5px 15px;
        background-color: var(--light-color);
        border-radius: 20px;
        font-size: 14px;
        cursor: pointer;
        transition: all 0.3s;
    }

    .category-tag:hover, .category-tag.active {
        background-color: #333;
        color: #fff;
    }

    /* 文章列表 - 图片在左，内容在右 */
    .article-list {
        display: grid;
        grid-template-columns: 1fr;
        gap: 20px;
        margin-bottom: 40px;
    }

    .article-card {
        background-color: var(--white);
        border-radius: var(--radius-md);
        overflow: hidden;
        box-shadow: var(--shadow-sm);
        transition: transform 0.3s, box-shadow 0.3s;
        display: flex;
    }

    .article-card:hover {
        transform: translateY(-3px);
        box-shadow: var(--shadow-md);
        cursor: pointer;
    }

    .article-image-container {
        height: 180px;
        max-width: 269px;
    }

    .article-image {
        width: 100%;
        height: 100%;
        object-fit: cover;
        transition: transform 0.3s;
    }

    .article-card:hover .article-image {
        transform: scale(1.05);
    }

    .article-content {
        padding: 20px;
        flex: 1;
        display: flex;
        flex-direction: column;
    }

    .article-meta {
        display: flex;
        justify-content: space-between;
        margin-bottom: 10px;
        font-size: 14px;
        color: var(--light-text);
    }

    .article-category {
        font-size: 12px;
        display: inline-block;
        margin-bottom: 10px;
        
    }

    .article-category span{
        background-color: #333;
        color: #fff;
        border-radius: var(--radius-sm);
        padding: 2px 10px 5px 10px;
        margin-right: 10px;
    }

    .article-title {
        font-size: 18px;
        margin-bottom: 10px;
        line-height: 1.4;
        display: -webkit-box;
        -webkit-line-clamp: 1; /* 限制显示行数 */
        -webkit-box-orient: vertical;
        overflow: hidden;
        text-overflow: ellipsis;
    }

    .article-excerpt {
        color: var(--light-text);
        margin-bottom: 15px;
        line-height: 1.6;
        display: -webkit-box;
        -webkit-line-clamp: 1; /* 限制显示行数 */
        -webkit-box-orient: vertical;
        overflow: hidden;
        text-overflow: ellipsis;
    }

    .read-more {
        display: inline-block;
        padding: 8px 15px;
        background-color: var(--primary-color);
        color: var(--white);
        border-radius: var(--radius-sm);
        text-decoration: none;
        font-size: 14px;
        transition: background-color 0.3s;
        align-self: flex-start;
    }

    .read-more:hover {
        background-color: var(--secondary-color);
    }

    /* 分页 */
    .pagination {
        display: flex;
        justify-content: center;
        gap: 10px;
        margin-bottom: 40px;
    }

    .page-item {
        list-style: none;
    }

    .page-link {
        display: block;
        outline: none;
        padding: 8px 15px;
        background-color: var(--white);
        border: 1px solid #ddd;
        border-radius: var(--radius-sm);
        color: var(--text-color);
        text-decoration: none;
        transition: all 0.3s;
    }

    .page-link:hover {
        background-color: var(--light-color);
        background-color: #333;
        color: #fff;
    }

    .page-link.active {
        background-color: #333;
        color: #fff;
    }

    /* 响应式设计 */
    @media (max-width: 768px) {
        .container {
            padding: 5rem 10px;
        }
        .article-card {
            flex-direction: column;
        }
        
        .article-image-container {
            width: 100%;
            max-width: 100%;
            height: 200px;
        }
        
        .filter-section {
            flex-direction: column;
            gap: 15px;
        }
        
        .search-container, .category-filter {
            width: 100%;
        }
    }

    @media (min-width: 769px) {
        .container{
            min-width: 800px;
            max-width: 950px;
        }
    }
</style>